package com.soilflow.info.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.soilflow.common.annotation.DataScope;
import com.soilflow.common.constant.MqConstants;
import com.soilflow.common.domain.LandAuction;
import com.soilflow.common.domain.LandAuctionPrice;
import com.soilflow.common.domain.dto.LandAuctionPriceDto;
import com.soilflow.common.domain.vo.LandAuctionPriceVo;
import com.soilflow.common.exception.ServiceException;
import com.soilflow.common.mybatisplus.BaseEntity;
import com.soilflow.common.utils.DateUtils;
import com.soilflow.framework.web.domain.server.Sys;
import com.soilflow.framework.websocket.WebSocketUsers;
import com.soilflow.info.mapper.LandAuctionMapper;
import com.soilflow.info.mapper.LandAuctionPriceMapper;
import com.soilflow.info.service.LandAuctionPriceService;
import org.apache.ibatis.plugin.Intercepts;
import org.omg.CORBA.INTERNAL;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LandAuctionPriceServiceImpl extends ServiceImpl<LandAuctionPriceMapper, LandAuctionPrice> implements LandAuctionPriceService {


    @Resource
    private LandAuctionPriceMapper landAuctionPriceMapper;

    @Resource
    private LandAuctionMapper landAuctionMapper;

    @Resource
    private RabbitTemplate rabbitTemplate;




    @DataScope(deptAlias = "lap")
    @Override
    public List<LandAuctionPriceVo> auctionPriceList(LandAuctionPriceDto dto) {
        return landAuctionPriceMapper.auctionPriceList(dto);
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized Boolean addAuctionPrice(LandAuctionPriceDto dto) throws ParseException {
        //查询竞拍结束时间
        LambdaQueryWrapper<LandAuction> auctionQuery = new LambdaQueryWrapper<>();
        auctionQuery.eq(dto.getAuctionId() != null, BaseEntity::getId, dto.getAuctionId()).last("limit 1");
        LandAuction landAuction = null;
        landAuction = landAuctionMapper.selectOne(auctionQuery);
        if (ObjectUtils.isEmpty(landAuction)) {
            return false;
        }

        //校验时间差
        String auctionEnd = landAuction.getAuctionEnd();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date auctionEndDate = sdf.parse(auctionEnd);
        Long diffTime = (auctionEndDate.getTime() - System.currentTimeMillis()) / 1000 / 60;
        //大于三分钟再加五分钟
        if (diffTime <= 3) {
            Date date = DateUtils.addMinutes(auctionEndDate, 5);
            LandAuction update = new LandAuction();
            update.setId(dto.getAuctionId());
            update.setAuctionEnd(sdf.format(date));
            landAuctionMapper.updateById(update);
        }


        /**
         * 插入报价表
         */
        // 插入报价前校验是否已经报价
        QueryWrapper<LandAuctionPrice> landAuctionPriceQueryWrapper = new QueryWrapper<>();
        landAuctionPriceQueryWrapper.lambda().eq(LandAuctionPrice::getAuctionId,dto.getAuctionId())
                .eq(LandAuctionPrice::getUserId,dto.getUserId()).last("limit 1");
        LandAuctionPrice landAuctionPrice = this.getOne(landAuctionPriceQueryWrapper);
        if (ObjectUtils.isEmpty(landAuctionPrice)){
            // 插入
            LandAuctionPrice landAuctionPrice2 = new LandAuctionPrice();
            BeanUtils.copyProperties(dto, landAuctionPrice2);
            System.out.println("landAuctionPrice = " + landAuctionPrice2);
            landAuctionPriceMapper.insert(landAuctionPrice2);
        }else {
            landAuctionPrice.setPrice(dto.getPrice());
            landAuctionPriceMapper.updateById(landAuctionPrice);
            //throw new ServiceException("请勿重复竞拍！");
        }



        //同步最新倒计时和出价
        landAuction = landAuctionMapper.selectOne(auctionQuery);
        LambdaQueryWrapper<LandAuctionPrice> priceQuery = new LambdaQueryWrapper<>();
        priceQuery.orderByDesc(LandAuctionPrice::getAuctionTime).last("limit 1");

        BigDecimal price = landAuctionPriceMapper.selectOne(priceQuery).getPrice();
        String getDao = DateUtils.getDatePoo2(landAuction.getAuctionEnd(), DateUtils.getTime(), price);
        WebSocketUsers.sendMessageToUsersByText(getDao);

        //校验竞拍结束时间
        Long auctionTime = sdf.parse(landAuction.getAuctionEnd()).getTime();
        Long currentTime = System.currentTimeMillis();
        if (auctionTime > currentTime){
            Long delayTime = auctionTime - currentTime;
            Map dataMap = new HashMap();
            dataMap.put("id",landAuction.getId());
            dataMap.put("type","auctionEndDelayTime");
            //发送延迟修改状态信息
            String message = JSON.toJSONString(dataMap);
            rabbitTemplate.convertAndSend(MqConstants.DELAYED_EXCHANGE_NAME, MqConstants.AUCTION_PUBLISH_KEY,message, messagePostProcessor -> {
                messagePostProcessor.getMessageProperties().setDelay(Integer.parseInt(delayTime.toString()));
                return messagePostProcessor;
            });
        }

        return true;

    }
}
